﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using LikeTryCore;
using Contract;

namespace ApplyGoods
{
    public partial class Service1 : ServiceBase
    {
        private Thread[] TaskThread;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                List<LikeAccount> accountObj = LikeTry.GetAccountList();
                if (accountObj != null && accountObj.Count > 0)
                {
                    TaskThread = new Thread[accountObj.Count];
                    LikeTry.FillGoodLists(1);
                    for (int i = 0; i < accountObj.Count; i++)
                    {
                        LikeTry liketry = new LikeTry(accountObj[i].Cookies);
                        liketry.KeepOnline();
                        TaskThread[i] = new Thread(liketry.RequestGood);
                        TaskThread[i].IsBackground = true;
                        TaskThread[i].Priority = ThreadPriority.Highest;
                        TaskThread[i].Name = accountObj[i].Name + accountObj[i].Id.ToString();
                        TaskThread[i].Start(accountObj[i]);
                    }

                    Thread getGoods = new Thread(LikeTry.FillGoodLists);
                    getGoods.IsBackground = true;
                    getGoods.Priority = ThreadPriority.Highest;
                    getGoods.Name = "Get Goods";
                    getGoods.Start();
                }
            }
            catch (Exception eeepo)
            {
                EventLog.WriteEntry("Application", eeepo.Message + eeepo.StackTrace, EventLogEntryType.Error);
                throw;
            }
        }

        protected override void OnStop()
        {
            try
            {
                if (TaskThread != null)
                {
                    foreach (var item in TaskThread)
                    {
                        item.Abort();
                    }
                }
            }
            catch (Exception exp)
            { }
        }
    }
}
